package titt.server.service.db;

import titt.key.TITTKey;
import titt.server.os.ObjectServer;
import titt.server.service.Service;
import titt.server.service.invoker.TITTInternalInvoker;

public class TITTDBEventDispatcher implements ServerDatabase {

	private final ServerDatabase db;
	private final Dispatcher removal = new Dispatcher("tittRemoved"), added = new Dispatcher("tittAdded");
	private final ObjectServer os;
	
	public TITTDBEventDispatcher(ObjectServer os, ServerDatabase db) {
		this.db = db;
		this.os = os;
	}

	public boolean containsDuplicateKey(TITTKey key) {
		return db.containsDuplicateKey(key);
	}
	
	public void add(Service s) {
		db.add(s);
		added.dispatchEvent(s);
		attachListeners(s);
	}

	public Service get(String id) {
		return db.get(id);
	}

	public Service get(TITTKey key) {
		return db.get(key);
	}

	public Service[] getAll() {
		return db.getAll();
	}

	public Service remove(String id) {
		final Service s = db.remove(id);
		
		if(s == null) return null;
				
		added.removeListener(s);
		removal.removeListener(s);
		
		removal.dispatchEvent(s);
		
		return s;
	}
	
	private void attachListeners(Service s) {
		TITTInternalInvoker inv = new TITTInternalInvoker(s.getID(), os);
		
		added.attachListener(s, inv);
		removal.attachListener(s, inv);
	}
	
}
